﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
using System.Xml;
using CustomControl;
using TeacherLeftHand.View;
using RichTextBox = Microsoft.Windows.Controls.RichTextBox;

namespace TeacherLeftHand.Util
{
    public class Utility
    {

        /// <summary>
        /// Serializes <code>obj</code> into a XAML string
        /// </summary>
        /// <param name="obj">Object to serialize</param>
        /// <returns>Serialized XAML version of <code>obj</code></returns>
        public static string SerializeObject(object obj)
        {
    
            return XamlWriter.Save(obj);
        }

        /// <summary>
        /// Converts XAML serialized string back into object
        /// </summary>
        /// <param name="xaml">XAML serialized object</param>
        /// <returns>Object represented by XAML string</returns>
        public static object DeserializeObject(string xaml)
        {
            return XamlReader.Load(new XmlTextReader(new StringReader(xaml)));
        }

        /// <summary>
        /// Clones an object
        /// </summary>
        /// <param name="obj">object to clone</param>
        /// <returns>Clone of <code>obj</code></returns>
        public static object CloneElement(object obj)
        {
            return DeserializeObject(SerializeObject(obj));
        }
        public static T TryFindParent<T>(DependencyObject child) where T : DependencyObject
        {
            //get parent item
            DependencyObject parentObject = GetParentObject(child);

            //we've reached the end of the tree
            if (parentObject == null) return null;

            //check if the parent matches the type we're looking for
            T parent = parentObject as T;
            if (parent != null)
            {
                return parent;
            }
            else
            {
                //use recursion to proceed with next level
                return TryFindParent<T>(parentObject);
            }
        }
        public static DependencyObject GetParentObject(DependencyObject child)
        {
            if (child == null) return null;

            //handle content elements separately
            var contentElement = child as ContentElement;
            if (contentElement != null)
            {
                var parent = ContentOperations.GetParent(contentElement);
                if (parent != null) return parent;

                var fce = contentElement as FrameworkContentElement;
                return fce != null ? fce.Parent : null;
            }

            //also try searching for parent in framework elements (such as DockPanel, etc)
            var frameworkElement = child as FrameworkElement;
            if (frameworkElement != null)
            {
                var parent = frameworkElement.Parent;
                if (parent != null) return parent;
            }

            //if it's not a ContentElement/FrameworkElement, rely on VisualTreeHelper
            return VisualTreeHelper.GetParent(child);
        }
        public static IEnumerable<UIElement> GetInlineControls(RichTextBox rtb)
        {

            foreach (Block b in rtb.Document.Blocks)
            {
                if (b is Paragraph)
                {
                    foreach (Inline inline in ((Paragraph)b).Inlines)
                    {
                        if (inline is InlineUIContainer)
                        {
                            var uiContainer = (InlineUIContainer)inline;
                            if (uiContainer.Child is ListBox)
                            {

                                yield return (uiContainer.Child);
                            }

                        }
                    }
                }
            }

        }

        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }
        public static void LoadRTF(string rtf, RichTextEditor richTextBox)
        {

            if (string.IsNullOrEmpty(rtf))
            {
                throw new ArgumentNullException();
            }

            var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);

            //Create a MemoryStream of the Rtf content

            using (var rtfMemoryStream = new MemoryStream())
            {
                using (var rtfStreamWriter = new StreamWriter(rtfMemoryStream))
                {
                    rtfStreamWriter.Write(rtf);
                    rtfStreamWriter.Flush();
                    rtfMemoryStream.Seek(0, SeekOrigin.Begin);

                    //Load the MemoryStream into TextRange ranging from start to end of RichTextBox.
                    textRange.Load(rtfMemoryStream, DataFormats.Rtf);
                }
            }
        }

        public static IEnumerable<UIElement> GetInlineRichTextBoxs(RichTextEditor rtb)
        {

            foreach (Block b in rtb.Document.Blocks)
            {
                if (b is Paragraph)
                {
                    foreach (Inline inline in ((Paragraph)b).Inlines)
                    {
                        if (inline is InlineUIContainer)
                        {
                            var uiContainer = (InlineUIContainer)inline;
                            if (uiContainer.Child is RichTextEditor)
                            {
                                yield return (uiContainer.Child);
                            }
                        }
                    }
                }
            }

        }
        public static void ProcessBeforeSaving(Inline i)
        {
            var inlineType = i.GetType();

            if (inlineType == typeof(InlineUIContainer))
            {
                //The inline has an object, likely an IMAGE!!!
                var uic = ((InlineUIContainer)i);
                //if it is an image

                if (uic.Child.GetType() == typeof(InlineRichTextBox))
                {
                    var temp = (InlineRichTextBox)uic.Child;
                    temp.ClearValue(InlineRichTextBox.ContextMenuProperty);
                }
            }
            else if (inlineType == typeof(Span))
            {
                foreach (var spanInline in ((Span)i).Inlines)
                {
                    ProcessBeforeSaving(spanInline);
                }
            }
            else if (inlineType == typeof(AnchoredBlock))
            {
                foreach (var block in ((AnchoredBlock)i).Blocks)
                {
                    ProcessBeforeSaving(block);
                }
            }
        }

        public static void ProcessBeforeSaving(Block b)
        {
            if (b is Paragraph)
            {
                foreach (Inline i in ((Paragraph)b).Inlines)
                {
                    ProcessBeforeSaving(i);
                }
            }
            else if (b is Table)
            {
                foreach (var tableRowGroup in ((Table)b).RowGroups)
                {
                    foreach (var row in tableRowGroup.Rows)
                    {
                        foreach (var cell in row.Cells)
                        {
                            foreach (var block in cell.Blocks)
                            {
                                ProcessBeforeSaving(block);
                            }
                        }
                    }
                }
            }
            else if (b is List)
            {
                foreach (var listItem in ((List)b).ListItems)
                {
                    foreach (var block in listItem.Blocks)
                    {
                        ProcessBeforeSaving(block);
                    }
                }
            }
            else if (b is Section)
            {
                foreach (var block in ((Section)b).Blocks)
                {
                    ProcessBeforeSaving(block);
                }
            }
            else if (b is BlockUIContainer)
            {
                foreach (var rtb in Utility.FindVisualChildren<RichTextEditor>(((BlockUIContainer)b).Child))
                {
                    foreach (var block in rtb.Document.Blocks)
                    {
                        ProcessBeforeSaving(block);
                    }
                }
            }

        }
    }
}
